﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Kaixin
{
    using Kaixin.Tools;
    using Kaixin.House.Garden;

    public class Friend
    {
        private string _name;
        private string _uid;

        public Friend(string name, string uid)
        {
            _name = name;
            _uid = uid;
        }

        public string Name
        {
            get 
            {
                return _name;
            }
        }

        public string Uid
        {
            get
            {
                return _uid;
            }
        }
    }

    public class FriendList
    {
        private List<Friend> _FriendList = new List<Friend>();
        private string _uid;    // myself uid
        private string _verify;
        private Network _network;

        public List<Friend> Items
        {
            get
            {
                return _FriendList;
            }
            set
            {
                _FriendList = value;
            }
        }

        public FriendList(Network network, string uid, string verify)
        {
            _network = network;
            _uid = uid;
            _verify = verify;
        }

        public void UpdateFriendList()
        {
            _FriendList.Clear();
            string baseURL = Consts.RootURL + Consts.FriendsListUrl;
            string url = baseURL + "?verify=" + _verify;

            try
            {
                // add myself first
                _FriendList.Add(new Friend("MySelf", _uid));

                string resp = _network.CallUrl(url);
                string pat = "<a href=\"javascript:gotoUser\\((\\d+?)\\);\" class=\"sl\">([^<]+?)</a>";

                Match m = Regex.Match(resp, pat);
                while (m.Success)
                {
                    _FriendList.Add(new Friend(m.Groups[2].Value, m.Groups[1].Value));
                    m = m.NextMatch();
                }
            }
            catch (Exception)
            {
            }
        }

        public Friend GetFriendByUid(string uid)
        {
            for (int i = 0; i < _FriendList.Count; i++)
            {
                if (_FriendList[i].Uid.Equals(uid))
                    return _FriendList[i];
            }
            return null;
        }
    }
}
